<template>
  <a-modal v-model:visible="modifyPasswd.visible" @ok="modifyPasswd.handleOk" @cancel="modifyPasswd.handleCancel"
           @before-close="modifyPasswd.model = {};" :footer="false"
           :hide-cancel="true">
    <template #title>
      修改密码
    </template>

    <a-form :model="modifyPasswd.model" :label-col-props="{span: 4, offset: 0}"
            @submit-success="modifyPassword">
      <a-form-item field="oldPassword"
                   :rules="[{required:true,message:'当前密码不能为空'},{minLength:4,message:'至少四个字符'}]"
                   :validate-trigger="['change','input']" size="large" title="当前密码">
        <a-input-password
            v-model="modifyPasswd.model.oldPassword" :max-length="16"
            placeholder="当前密码" allow-clear
        >
          <template #prefix>
            <icon-lock/>
          </template>
        </a-input-password>

      </a-form-item>
      <a-form-item field="password"
                   :rules="[{required:true,message:'新密码不能为空'},{minLength:6,maxLength:16, message:'6~16个字符'},{validator:validatePassword}]"
                   :validate-trigger="['change','input']" size="large">
        <a-input-password placeholder="新密码" allow-clear v-model="modifyPasswd.model.password"
        >
          <template #prefix>
            <icon-lock/>
          </template>
        </a-input-password>
        <template #extra>
          <div>6~16个字符,仅含且必须含有数字和字母以及在"!@#$%^&*?"中的特殊字符</div>
        </template>
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" type="primary">
          确定
        </a-button>
      </a-form-item>
    </a-form>

  </a-modal>
  <a-modal v-model:visible="loginDialog.visible"
           :closable="false" :mask-closable="false" :hide-cancel="true" :footer="false">
    <template #title>
      账号登录
    </template>
    <div>
      <a-form :model="form" :label-col-props="{span: 2, offset: 0}" @submit-success="login">
        <a-form-item field="username"
                     :rules="[{required:true,message:'账号不能为空'},{minLength:4,message:'至少四个字符'}]"
                     :validate-trigger="['change','input']">
          <a-input v-model="form.username" placeholder="账号" allow-clear :max-length="16" size="large">
            <template #prefix>
              <icon-user/>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item field="password" :rules="[{required:true,message:'密码'},{minLength:4,message:'至少六个字符'}]"
                     :validate-trigger="['change','input']">
          <a-input-password v-model="form.password" placeholder="密码" allow-clear :max-length="16" size="large">
            <template #prefix>
              <icon-lock/>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item field="captcha" :rules="[{required:true,message:'验证码'},{minLength:4,message:'需要四个字符'}]"
                     :validate-trigger="['change','input']">
          <a-input v-model="form.captcha" placeholder="验证码" allow-clear :max-length="4" size="large">
            <template #prefix>
              <icon-safe/>
            </template>
          </a-input>
          <img :src="captcha_url" id="captcha" @click="nextImg" title="看不清换一张" alt="验证码"/>
        </a-form-item>
        <a-form-item>
          <a-button status="warning" size="large" title="登录" html-type="submit">
            <template #icon>
              <icon-import/>
            </template>
            登&nbsp;录
          </a-button>
        </a-form-item>
      </a-form>
    </div>


  </a-modal>
  <a-layout class="layout-zero">
    <a-layout-sider
        hide-trigger
        collapsible
        :collapsed="collapsed"
    >
      <div class="logo" v-show="!collapsed">
        <div
            id="main_title" class="title_line">Light
        </div>
      </div>
      <a-menu
          :style="{ width: '100%' }"
          @menuItemClick="menuItemClick" :selected-keys="checkedPage"
      >
        <a-sub-menu key="main">
          <template #title>
            <span><IconMobile/>设备</span>
          </template>
          <a-menu-item :key="switch_page.camera">
            <icon-video-camera/>
            {{ switch_page.camera.title }}
          </a-menu-item>
          <a-menu-item :key="switch_page.default_area">
            <icon-home/>
            {{ switch_page.default_area.title }}
          </a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="user">
          <template #title>
            <span><icon-user-group/>用户</span>
          </template>
          <a-menu-item :key="switch_page.user">
            <icon-user/>
            {{ switch_page.user.title }}
          </a-menu-item>
          <a-menu-item :key="switch_page.dev_account">
            <icon-idcard/>
            {{ switch_page.dev_account.title }}
          </a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="settings">
          <template #title>
            <span><icon-settings />系统设置</span>
          </template>
          <a-menu-item :key="switch_page.pc_settings">
            <icon-file />
            {{ switch_page.pc_settings.title }}
          </a-menu-item>
        </a-sub-menu>
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-header>
        <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
          <a-col :span="1"/>
          <a-col :span="2">
            <a-button shape="round" @click="onCollapse">
              <template #icon>
                <IconCaretRight v-if="collapsed"/>
                <IconCaretLeft v-else/>
              </template>
            </a-button>
          </a-col>
          <a-col :span="17"/>
          <a-col :span="2">
            <a-trigger trigger="click" :unmount-on-close="false">
              <a-button>
                <template #icon>
                  <icon-user/>
                </template>
                {{ currentUser.username }}
              </a-button>

              <template #content>
                <div class="user_info_pc">
                  <a-space direction="vertical" fill>
                    <div class="user_info_item_pc">
                      <a-space>
                        <span>用户名</span>
                        <span>{{ currentUser.username }}</span>
                      </a-space>
                    </div>
                    <div class="user_info_item_pc">
                      <a-space>
                        <span>账号</span>
                        <span>{{ currentUser.account }}</span>
                      </a-space>
                    </div>
                    <div class="user_info_item_pc click_able" @click="this.modifyPasswd.visible = true;">
                      <a-space>
                        <icon-lock/>
                        <span>修改密码</span>
                      </a-space>
                    </div>
                    <div class="user_info_item_pc click_able" @click="logout">
                      <a-space>
                        <icon-export/>
                        <span>注销</span>
                      </a-space>
                    </div>
                  </a-space>
                </div>
              </template>
            </a-trigger>
          </a-col>
          <a-col :span="1">
            <a-button type="dashed" @click="onSwitchLights">
              <template #icon>
                <icon-moon-fill v-if="lightOn"/>
                <icon-sun-fill v-else/>
              </template>
            </a-button>
          </a-col>
        </a-row>

      </a-layout-header>
      <a-layout style="padding: 0 24px;">
        <a-breadcrumb :style="{ padding: '16px 0' }">
          <a-breadcrumb-item>Home</a-breadcrumb-item>
          <a-breadcrumb-item>{{ thisPage }}</a-breadcrumb-item>
        </a-breadcrumb>
        <a-layout-content>
          <router-view/>
        </a-layout-content>
        <a-layout-footer>Footer</a-layout-footer>
      </a-layout>
    </a-layout>
  </a-layout>
</template>
<script>
import {
  IconCaretLeft, IconCaretRight,
  IconVideoCamera,
  IconMobile,
  // IconDesktop,
  IconMoonFill,
  // IconPlusCircle,
  IconSunFill,
  IconHome, IconUser, IconUserGroup, IconIdcard, IconLock, IconImport, IconExport, IconSafe, IconSettings
    ,IconFile
  // IconApps
} from '@arco-design/web-vue/es/icon';
import switch_page from "@/js/switch_page";
import {get, postP, postPK} from "@/js/axios_util";
import {Message} from "@arco-design/web-vue";
import {doExchange, doExchangeByCachePk} from "@/js/dh";
import dhPublicKey from "@/js/dh";
import {getLoginErrorMsg, getUserError} from "@/js/error_code";
import {validatePassword} from "@/js/validator";
import {img_svg} from "@/js/res";
import {cmdChannel} from "@/js/on_start";
import {initSettings} from "@/js/sysSettings";

const currentUser = "currentUser";
export default {
  components: {
    IconCaretRight, IconCaretLeft, IconMoonFill,
    IconSunFill, IconHome,
    IconMobile,
    IconUser,
    // IconDesktop, IconPlusCircle,
    // IconApps,
    IconVideoCamera,
    IconUserGroup,
    IconIdcard,
    IconLock,
    IconImport,
    IconExport,
    IconSafe,
    IconSettings,IconFile
  },
  name: 'pc',
  data() {
    return {
      collapsed: false,
      lightOn: document.body.getAttribute('arco-theme') !== 'dark',
      thisPage: '',
      switch_page,
      checkedPage: [],
      loginDialog: {
        visible: false
      }, form: {
        username: '',
        password: '',
        captcha: ''
      },
      captcha_url: img_svg,
      captcha_url_switch: 1,
      currentUser: {},
      modifyPasswd: {
        visible: false,
        model: {
          password: "",
          oldPassword: "",
        }

      }
    }
  },

  beforeRouteUpdate(to) {
    let location = switch_page[to.name];
    this.thisPage = location.title
    this.checkedPage[0] = location
  },
  created() {
    const showLoginDialog = () => {
      this.loginDialog.visible = true;
      let captcha_url = '/login/captcha';
      if (process.env.NODE_ENV === 'development') {
        captcha_url = window.dev.httpUrlBase + captcha_url;
      }
      this.captcha_url = captcha_url;
      this.form.captcha = '';
    }

    let item = localStorage.getItem(currentUser);
    let theCurrentUser = JSON.parse(item);
    if (!theCurrentUser || !theCurrentUser.account) {

      showLoginDialog();
      return
    }
    get('/login/isLogin', resp => {
      if (!resp.data) {
        showLoginDialog();
      } else {
        this.loginDialog.visible = false;
        this.currentUser = theCurrentUser;
        this.connectWs();
        initSettings();
      }
    })

  },
  methods: {
    validatePassword,
    nextImg() {
      let url = '/login/captcha';
      if (process.env.NODE_ENV === 'development') {
        url = window.dev.httpUrlBase + url;
      }
      this.captcha_url = url
      //刷新vue
      this.captcha_url_switch = this.captcha_url_switch ? 0 : 1;
      this.captcha_url = url + "?new=" + this.captcha_url_switch;
    }
    ,connectWs(){
      if(!cmdChannel.isConnected()){
        cmdChannel.connect((eve) => Message.info({content: `${eve.data}`, showIcon: true}))
      }

    },
    onCollapse() {
      this.collapsed = !this.collapsed;
    },
    onSwitchLights() {
      this.lightOn = !this.lightOn
      let body = document.body;
      if (this.lightOn) {
        body.removeAttribute('arco-theme');
        localStorage.setItem('arco-theme-dark', '0');
      } else {
        body.setAttribute('arco-theme', 'dark');
        localStorage.setItem('arco-theme-dark', '1');
      }
    }, menuItemClick(page) {
      switch_page.switchPageTo(page);
    }, login() {
      doExchange((keyAgreeResult, aesEncode) => {
        let loginData = {
          account: aesEncode(this.form.username, keyAgreeResult.secret),
          password: aesEncode(this.form.password, keyAgreeResult.secret),
          captcha: aesEncode(this.form.captcha, keyAgreeResult.secret),
        }

        this.form.captcha = '';
        postP('/login/doLogin', loginData, {
          headers: {
            exchangeSessionId: keyAgreeResult.exchangeSessionId,
            publicKey: keyAgreeResult.publicKey
          }
        }, resp => {
          let data = resp.data;
          if (data.success) {
            this.loginDialog.visible = false;
            this.currentUser = data.result.user;
            let user = JSON.stringify(data.result.user);
            localStorage.setItem(currentUser, user);
            localStorage.setItem(dhPublicKey, JSON.stringify(data.result.dhPublicKey));
            this.form.password = '';
            this.connectWs();
            initSettings();
            return
          }
          const reason = getLoginErrorMsg(data.statusCode);
          Message.error({content: `登录失败[${reason}]`, showIcon: true})
          this.nextImg();

        })
      })


    }, logout() {
      let toLogin = () => {
        localStorage.removeItem(currentUser);
        //switch_page.switchPageTo(switch_page.m.login, {});
        location.reload();
      }
      get('/login/logout', toLogin, toLogin)

    }, modifyPassword() {
      doExchangeByCachePk((keyAgreeResult, aesEncode) => {
        let url = '/user/modifyPassword';
        postPK(url, {
          password: aesEncode(this.modifyPasswd.model.password, keyAgreeResult.secret),
          oldPassword: aesEncode(this.modifyPasswd.model.oldPassword, keyAgreeResult.secret)
        }, keyAgreeResult, resp => {
          let data = resp.data;
          if (data.success) {
            Message.info({content: "修改成功", showIcon: true});
            this.modifyPasswd.visible = false;
            return
          }
          const reason = getUserError(data.statusCode);
          Message.error({content: `操作失败[${reason}]`, showIcon: true})
        })
      })
    }

  }
}

</script>
<style scoped>
.layout-zero {
  background: var(--color-fill-2);
  border: 1px solid var(--color-border);
}

.layout-zero :deep(.arco-layout-sider) .logo {
  height: 32px;
  margin: 12px 8px;
  background: rgba(255, 255, 255, 0.2);
}

.layout-zero :deep(.arco-layout-sider-light) .logo {
  background: var(--color-fill-2);
}

.layout-zero :deep(.arco-layout-header) {
  height: 64px;
  line-height: 64px;
  background: var(--color-bg-3);
}

.layout-zero :deep(.arco-layout-footer) {
  height: 48px;
  color: var(--color-text-2);
  font-weight: 400;
  font-size: 14px;
  line-height: 48px;
}

.layout-zero :deep(.arco-layout-content) {
  color: var(--color-text-2);
  font-weight: 400;
  font-size: 14px;
  background: var(--color-bg-3);
}

.layout-zero :deep(.arco-layout-footer),
.layout-zero :deep(.arco-layout-content) {
  flex-direction: column;
  justify-content: center;
  color: var(--color-white);
  font-size: 16px;
  font-stretch: condensed;
}

.arco-layout {
  background: var(--color-bg-3);
  box-sizing: border-box;
  height: 100%;
}

.arco-breadcrumb {
  background: var(--color-bg-3);
  box-sizing: border-box;
  border-bottom: 1px solid var(--color-border);
  margin: 0 0 10px 0 !important;
  padding: 16px 0;
  /*border-radius: var(--border-radius-medium);*/
}

#main_title {
  display: inline-block !important;
  vertical-align: middle;
  text-align: center;
  line-height: 30px;
  height: 30px;
  font-size: 15px;
  font-weight: bold;
  font-style: italic;
  color: #42b983;
}

.arco-layout-content {
  display: block !important;
}

.title_line {
  margin-left: 5px;
  margin-right: 0;
  display: inline-block !important;
}

.arco-col {
  display: inline-block !important;
}

.arco-col {
  height: 90px;
  color: var(--color-text-2);
  margin: 16px 0 16px 0;
}

.console-item .arco-col > div {

  justify-content: center;
  height: 100%;
  border-radius: 5px 5px 5px 5px;
}

.console-item .arco-col:nth-child(2n) > div {
  background-color: rgba(var(--cyan-4), 0.9);
}

.console-item .arco-col:nth-child(2n + 1) > div {
  background-color: rgba(var(--red-3, 0.8));
}

#captcha {
  width: 9em;
}

.user_info_pc {

  color: var(--color-text-2);
  background: var(--color-bg-3);
  border-radius: 0.5em;
  box-shadow: 0px 0px 0px 1px rgb(var(--gray-3));
}

.user_info_item_pc {
  padding: 0.5em;
}

.click_able:hover {
  background: rgb(var(--gray-4));
  border-radius: 0 0 0.5em 0.5em;
}
</style>
